package com.zyh.homework.test4.domain;

import com.zyh.homework.test4.inter.Selector;
import com.zyh.homework.test4.inter.Touchable;

import java.util.Arrays;

public class MyArrayList implements Touchable {
    private Object[] all = new Object[2];
    private int total;

    //添加元素
    public void add(Object element) {
        if (total >= all.length) {
            all = Arrays.copyOf(all, all.length * 2);
        }
        all[total++] = element;
    }
    //删除元素


    void remove(int index) {
        if (index < 0 || index >= total) {
            System.out.println("没有这个元素");
            return;
        }
        System.arraycopy(all, index + 1, all, index, total - index - 1);
        all[--total] = null;
    }

    //替换元素
    public void set(int index, Object value) {
        if (index < 0 || index >= total) {
            System.out.println("没有这个元素");
            return;
        } else {
            all[index] = value;
        }
    }

    //获取index位置的元素
    public Object get(int index) {
        if (index < 0 || index >= total) {
            System.out.println("没有这个元素");
            return null;
        } else {
            return all[index];
        }
    }

    @Override
    public Selector select() {
        return new MySelector();
    }

    private class MySelector implements Selector {
        private int cursor;

        @Override
        public boolean hasNext() {
            return cursor != total;
        }

        @Override
        public Object next() {
            return all[cursor++];
        }
    }
}
